package com.googlecode.andronova;


import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.Menu.Item;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class FileBrowser extends ListActivity {
	
	 private enum DISPLAYMODE{ ABSOLUTE, RELATIVE; }

     private final DISPLAYMODE displayMode = DISPLAYMODE.ABSOLUTE;
     private List<String> directoryEntries = new ArrayList<String>();
     private File currentDirectory = new File("/");

     
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        browseToRoot();
    }
    
    
    /**
     * This function browses to the
     * root-directory of the file-system.
     */
    private void browseToRoot() {
         browseTo(new File("/"));
   } 
    
    
    /**
     * This function browses up one level
     * according to the field: currentDirectory
     */
    private void upOneLevel(){
         if(this.currentDirectory.getParent() != null)
              this.browseTo(this.currentDirectory.getParentFile());
    } 
    
    
    private void browseTo(final File aDirectory){
        if (aDirectory.isDirectory()){
             this.currentDirectory = aDirectory;
             fill(aDirectory.listFiles());
        }else{
             OnClickListener okButtonListener = new OnClickListener(){
                  // @Override
                  public void onClick(DialogInterface arg0, int arg1) {
                       try {
                    	   Uri uri= Uri.parse("file://"
                                   + aDirectory.getAbsolutePath());
                    	   
                    	   
                            // Lets start an intent to View the file, that was clicked...
                            Intent myIntent = new Intent(android.content.Intent.VIEW_ACTION,uri);
                                   
                            startActivity(myIntent);
                       } catch (Exception e) {
                            e.printStackTrace();
                       }
                  }
             };
             OnClickListener cancelButtonListener = new OnClickListener(){
                  // @Override
                  public void onClick(DialogInterface arg0, int arg1) {
                       // Do nothing
                  }
             };
            /* AlertDialog.show(this,"Question", "Do you want to open that file?\n"
                                      + aDirectory.getName(),
                                      "OK", okButtonListener,
                                      "Cancel", cancelButtonListener, false, null);*/

             new AlertDialog.Builder(this)
             .setTitle("Question")
             .setMessage("Do you want to open that file?" + aDirectory.getName())
             .setPositiveButton("OK", okButtonListener)
            .setNegativeButton("Cancel", cancelButtonListener)
            .show();
             
             
        }
   }

    
    
    private void fill(File[] files) {
        this.directoryEntries.clear();
        
        // Add the "." and the ".." == 'Up one level'
        try {
             Thread.sleep(10);
        } catch (InterruptedException e1) {
             // TODO Auto-generated catch block
             e1.printStackTrace();
        }
        this.directoryEntries.add(".");
        
        if(this.currentDirectory.getParent() != null)
             this.directoryEntries.add("..");
        
        switch(this.displayMode){
             case ABSOLUTE:
                  for (File file : files){
                       this.directoryEntries.add(file.getPath());
                  }
                  break;
             case RELATIVE: // On relative Mode, we have to add the current-path to the beginning
                  int currentPathStringLenght = this.currentDirectory.getAbsolutePath().length();
                  for (File file : files){
                       this.directoryEntries.add(file.getAbsolutePath().substring(currentPathStringLenght));
                  }
                  break;
        }
        
        ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this,
                  R.layout.file_row, this.directoryEntries);
        
        this.setListAdapter(directoryList);
   }

   protected void onListItemClick(ListView l, View v, int position, long id) {
        int selectionRowID = (int)this.getSelectedItemId();
        String selectedFileString = this.directoryEntries.get(selectionRowID);
        if (selectedFileString.equals(".")) {
             // Refresh
             this.browseTo(this.currentDirectory);
        } else if(selectedFileString.equals("..")){
             this.upOneLevel();
        } else {
             File clickedFile = null;
             switch(this.displayMode){
                  case RELATIVE:
                       clickedFile = new File(this.currentDirectory.getAbsolutePath()
                                                          + this.directoryEntries.get(selectionRowID));
                       break;
                  case ABSOLUTE:
                       clickedFile = new File(this.directoryEntries.get(selectionRowID));
                       break;
             }
             if(clickedFile != null)
                  this.browseTo(clickedFile);
        }
   } 
   
   @Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		super.onCreateOptionsMenu(menu);
		menu.add(0, 1, "Tag Editor", R.drawable.editor_small);
		menu.add(0, 2, "Lyrics", R.drawable.lyrics);
		menu.add(0, 3, "Library", R.drawable.folder_small);
		menu.add(0, 4, "Play List", R.drawable.favorite);
		menu.add(0, 5, "Help", R.drawable.help);
		menu.add(0,6,"File Browser",R.drawable.turnable);
	
		return true;
	}

   @Override
	public boolean onOptionsItemSelected(Item item) {
		// TODO Auto-generated method stub
		super.onOptionsItemSelected(item);
		
		switch(item.getId()) {		
	
		case 1:
			//Intent a = new Intent(this, TagEditor.class);
			//startActivity(a);
			return true;
			
		case 2:
	/*		Intent b = new Intent(this,Lyrics.class);
			startActivity(b);
			return true;*/
			
		case 3:
			Intent c = new Intent(this,LibraryActivity.class);
			startActivity(c);
			return true;
			
		case 4:
			//Intent d = new Intent(this,PlaylistEditor.class);
			//startActivity(d);
			return true;
		
		case 5:
			Intent e = new Intent(this,Help.class);
			startActivity(e);
			return true;
		
		case 6:
			Intent f = new Intent(this,AndroidFileBrowser.class);
			startActivity(f);
			return true;
		
		}
		return false;
	}
}